package cn.stylefeng.guns.sys.util;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

/**
 * @Author S-CH
 * @Date 2024/3/27 11:52
 * @Version 1.0
 */
public class DESUtil {

    // 固定的密钥
    private static final String FIXED_KEY = "zkhy@123456"; // 实际上这个应该是一个256位的密钥
    // 因为AES密钥是字节数组，需要一个固定的字节数组作为密钥
    private static final byte[] KEY_BYTES = Arrays.copyOf(FIXED_KEY.getBytes(StandardCharsets.US_ASCII), 32);

//    static {
//        // 对于AES-256，需要一个256位的密钥（32字节）
//        KEY_BYTES = FIXED_KEY.substring(0, 128).getBytes(); // 假设我们只使用128位AES
//    }

    public static String encrypt(String sSrc) throws Exception {
        if (sSrc == null) {
            return null;
        }
        SecretKeySpec skeySpec = new SecretKeySpec(KEY_BYTES, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        return Base64.getMimeEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String sSrc) throws Exception {
        if (sSrc == null) {
            return null;
        }
        SecretKeySpec skeySpec = new SecretKeySpec(KEY_BYTES, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        Base64.Decoder decoder = Base64.getMimeDecoder();
        byte[] encrypted1 = decoder.decode(sSrc);
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original);
    }


    public static void main(String[] args) throws Exception {
        // 需要加密的字串
        final Dict dict = new Dict();
        dict.set("account", "kaiguangui");
        dict.set("password", "123456");
//        String cSrc = "{\"account\":\"kaiguangui\",\"password\":\"123456\"}";
        final String x = JSONObject.toJSONString(dict);
        System.out.println(x);
        // 加密
        String s = x.replaceAll("\t", "").replaceAll("\n", "");

        String enString = encrypt(s);
        System.out.println("加密后的字串是：" + enString);
        // 解密
//        String enString = "yLKie/DthZNgHVNQm1b8iDNNOgjm4y43TiFfNeb+BUS2wmnwvcPWCDFYbdpqWghQ";
        String DeString = decrypt(enString);

        System.out.println("解密后的字串是：" + DeString);
    }
}
